package cn.cxq.learning.e1_1;

import static java.lang.Math.abs;
import static java.lang.Math.log;

public class LogDerivativeUtil {

    private static int max_loop = 51; //最大迭代次数
    private static int act_loop = 0; //实际迭代次数
    private static double EPS = 0.4E-10;//绝对误差
    private static double H[] = new double[max_loop]; //迭代步长
    private static double DTF[] = new double[max_loop]; //迭代值差
    private static double DQF[] = new double[max_loop]; //迭代中间值
    private static double ERR[] = new double[max_loop]; //迭代差值
    private static double step_length = 0.32; //初始步长

    private static double deltaF(double x, double sl) {
        return log((x + sl) / x);
    }

    public static double operation(double value) {
        for (act_loop = 0; act_loop < max_loop; act_loop++) {
            H[act_loop] = act_loop != 0 ? H[act_loop - 1] / 2 : step_length;
            DTF[act_loop] = deltaF(value, H[act_loop]);
            DQF[act_loop] = DTF[act_loop] / H[act_loop];
            ERR[act_loop] = act_loop != 0 ? abs(DQF[act_loop] - DQF[act_loop - 1]) : Double.MAX_VALUE;
            if (ERR[act_loop] < EPS) break;
        }
        return DQF[act_loop];
    }
}
